/**
js table
*/
Array.prototype.indexOf = function(value){
	for(var i = 0; i < this.length; i++){
		if(this[i] == value){
			return i;
		}
	}
	return -1;
}

function HappyTable(settings)
{
	var _self = this;

	var _settings = settings;

	//放置表格的最外层容器,通常为一个div
	var _view = document.body;

	var _rawView;

	//显示表格头的div节点,header div
	var _hd;

	var _lhd;

	var _lbd;

	//显示表格体的div节点,body div
	var _bd;

	//显示分页栏的div节点,pager div
	var _pd;

	//锁定数据表 html table
	var _lt;

	//活动数据表 html table
	var _at;

	//每个HappyTable对象的随机数字编号
	var _rn;

	var _loaded = false;

	var getDom = function(id){
		return document.getElementById(id);
	};

	//配置表格的最外层容器和样式表
	(function(){
		_rn = parseInt(Math.random() * 10000);

		if(!_settings.view){
			_view = document.body;
		}else{
			if(typeof(_settings.view) != 'object'){
				_view = getDom(_settings.view);
			}else{
				_view = _settings.view;
			}
			_view.style.position = 'absolute';
		}

		//为了准确拼接表格，必须指定行高度
		if(!_settings.rowHeight){
			_settings.rowHeight = 25;
		}

		//创建默认的css样式表
		var csss = {
			rowOdd : 'background-color:#ebf3fe;',
			rowEven : 'background-color:#f0f0f0;',
			rowHover: 'background-color:#ffffcc;',
			rowSelected : 'background-color:red;',
			header : 'background-color:#ccc;font-weight:bold;',
			table : 'background-color:white;',
			tools : 'overflow:hidden;padding-left:5px;border:1px solid #bbbbbb;background-color:#eeeeee;filter:alpha(opacity=80);opacity:0.8;font-size:12px;'
		};

		if(!_settings.css){
			_settings.css = {};
		}

		(function(){
			var head = document.getElementsByTagName('head')[0];
			var css = document.createElement('style');
			css.setAttribute('type', 'text/css');
			head.appendChild(css);
			for(var f in csss){
				var cssText = '.happy-table-' + f + '{'+ csss[f] +'}';
				try{
					var cs = document.createTextNode(cssText);
					css.appendChild(cs);
				}catch(e){
					css.styleSheet.cssText += cssText;
				}
				if(!_settings.css[f]){
					_settings.css[f] = 'happy-table-' + f;
				}
			}

		})();

		if(!_settings.pager){
			_settings.pager = {};
		}

		if(_settings.isPaging !== false && _settings.isPaging !== true){
			_settings.isPaging = true;
		}
	})();

	//初始化view
	var initView = function(){
		//绑定最外层容器的滚动事件
		_view.onscroll = function(ev){
			repairePosition();
			var ev = ev || event;
			_self.fire('view', 'scroll', _view, ev);
		}

		_view.onclick = function(ev){
			var ev = ev || event;
			_self.fire('view', 'click', _view, ev);
		}

		_view.onmouseover = function(ev){
			var ev = ev || event;
			_self.fire('view', 'mouseover', _view, ev);
		}

		_view.onmouseout = function(ev){
			var ev = ev || event;
			_self.fire('view', 'mouseout', _view, ev);
		}

		_view.draw = function(){
			_self.draw();
		}

		_view.data = _self.data;
	}

	initView();

	//把漂浮部分修正到合适的位置
	var repairePosition = function(){
		if(_rawView){
			var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
			var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
		}else{
			var scrollTop = _view.scrollTop;
			var scrollLeft = _view.scrollLeft;
		}

		if(_hd){
			_hd.style.top = scrollTop + 'px';
		}

		if(_pd){
			if(_rawView){
				var top = document.documentElement.clientHeight - 50 + scrollTop;
			}else{
				var top = (parseInt(_view.style.height) - 60 + scrollTop).toString();
			}
			_pd.style.top = top + 'px';
			_pd.style.left = (parseInt(_view.style.width) - parseInt(_pd.style.width) - 30 + scrollLeft).toString() + 'px' ;
		}

		var l = getDom('happyTable-lbs-' + _rn);
		if(l){
			l.style.left = scrollLeft + 'px';
			_lhd.style.top = scrollTop + 'px';
		}
	}

	var _select = function()
	{
		var s = document.getElementsByTagName('select');
		for(var i = 0; i < s.length; i++){
			s[i].style.visibility = ((!s[i].style.visibility || s[i].style.visibility == 'visible') ? 'hidden' : 'visible');
		}
	};

	var mask = {};
	mask.show = function(msg){
		if(mask.div){
			return;
		}
		mask.div = document.createElement('div');
		var c = {position:'absolute', textAlign:'center',verticalAlign:'middle',backgroundColor:'#cccccc', width:_view.style.width, height:_view.style.height,zIndex:1000,filter:'alpha(opacity=70)', opacity:0.7, top:_view.offsetTop + 'px', left:_view.offsetLeft + 'px'};
		for(var f in c){
			mask.div.style[f] = c[f];
		}
		var div = document.createElement('div');
		div.style.marginTop = '50px';
		div.innerHTML = msg;
		mask.div.appendChild(div);
		document.body.appendChild(mask.div);
	};

	mask.hide = function(){
		if(mask.div){
			document.body.removeChild(mask.div);
			mask.div = null;
		}
	};

	var _load = function(){
		_loaded = false;
		mask.show('正在加载数据...');
		_self.pager.setUrl();
		var handler = function(r){
			var rt = r.responseText;
			try{
				rt = _self.decode(rt);
				if(!_settings.header && rt.header){
					_settings.header = rt.header;
				}

				_settings.total = rt.total ? rt.total : rt.data.length;

				if(!_settings.header){
					var err = new Error('Table header lost');
				}

				if(_settings.op){
					_settings.header.happyTableOperation = {width:_settings.op.width, title: _settings.op.title ? _settings.op.title : '操作'};
				}

				if(!rt.data){
					new Error('Data lost');
				}
			}catch(e){
				alert(e.message);
			}
			_settings.data = rt.data;
			_self.data = rt.data;
			_loaded = true;
			mask.hide();
		};
		_settings.ajax({
			url : _settings.URL,
			success : handler
		});
	};

	var header = function()
	{
		//先对header排序，锁定的列排在前面，重新设定宽度
		(function(){
			var nh = {};
			var atw = 0, ltw = 0;
			for(var f in _settings.header){
				atw += _settings.header[f].width;

				if(_settings.header[f].locked){
					nh[f] = _settings.header[f];
					ltw += _settings.header[f].width;
				}
			}
			_settings.width = atw;
			_settings.lockedWidth = ltw;

			for(var f in _settings.header){
				if(!_settings.header[f].locked){
					nh[f] = _settings.header[f];
				}
			}
			_settings.header = nh;
		})();

		var h = _settings.header;

		var aht = document.createElement('table');
		aht.cellSpacing = 1;
		aht.cellPadding = 0;
		aht.className = _settings.css.table;
		var ahtr = aht.insertRow(-1);
		ahtr.className = _settings.css.header;

		var lht = document.createElement('table');
		lht.cellSpacing = 1;
		lht.cellPadding = 0;
		lht.className = _settings.css.table;
		var lhtr = lht.insertRow(-1);
		lhtr.className = _settings.css.header;

		var lock = function(field){
			for(var f in _settings.header){
				if(f == field){
					_settings.header[f].locked = _settings.header[f].locked ? false : true;
				}
			}
			_self.draw();
		}

		var filter = function(field){
			var f = h[field];
			if(!f.filter || !f.mapping){
				return;
			}
			var m = f.mapping;
			var sl = document.createElement('select');
			sl.addOption = function(op){
				try{
					sl.add(op, null);
				}catch(e){
					sl.add(op);
				}
			}
			var op = new Option(f.title, '');
			sl.addOption(op);
			for(var ff in m){
				var op = new Option(m[ff], ff);
				sl.addOption(op);
			}

			for(var i = 0; i < sl.options.length; i++){
				if(sl.options[i].value == f.filterValue){
					sl.options[i].selected = true;
				}
			}

			sl.onchange = function(ev){
				var tt = {};
				tt[field] = sl.value;
				f.filterValue = sl.value;
				_self.configUrl(tt);
				_self.show();
			}
			return sl;
		}

		for(var field in h){
			var cw = h[field].width - 2;

			var ahtd = ahtr.insertCell(-1);
			ahtd.title = '双击冻结该列';
			with(ahtd.style){
				width = h[field].width + 'px';
				height = _settings.rowHeight + 'px';
				cursor = 'pointer';
			}

			var celldiv = document.createElement('div');
			celldiv.style.width = cw + 'px';
			celldiv.style.overflow = 'hidden';

			var fil;
			if(h[field].filter && h[field].mapping){
				var fil = filter(field);
				//被锁定的列的最下层不生成过滤器
				if(h[field].locked){
					celldiv.appendChild(document.createTextNode(h[field].title));
				}else{
					celldiv.appendChild(fil);
				}
			}else{
				celldiv.appendChild(document.createTextNode(h[field].title));
			}

			ahtd.appendChild(celldiv);

			//js的双击事件会触发两次单击和一次双击，用此定时器来判断是否双击
			var dblclick = true;

			ahtd.ondblclick = (function(f){
				return function(){dblclick = true;lock(f);}
			})(field);

			//排序
			if(h[field].sort){
				ahtd.title += ',单击排序';
				ahtd.onclick = (function(f){
					return function(){
						dblclick = false;
						setTimeout(function(){if(!dblclick)_self.sort(f);}, 300);
					}
				})(field);
			}

			//生成被锁定的列
			if(h[field].locked){
				lhtd = lhtr.insertCell(-1);
				lhtd.title = '双击释放冻结';
				lhtd.style.cursor = 'pointer';
				lhtd.style.width = h[field].width + 'px';
				lhtd.style.height = _settings.rowHeight + 'px';

				lhtd.ondblclick = (function(f){
					return function(){dblclick = true;lock(f);}
				})(field);

				if(h[field].sort){
					lhtd.title += ',单击排序';
					lhtd.onclick = (function(f){
						return function(){
							dblclick = false;
							setTimeout(function(){if(!dblclick)_self.sort(f);}, 300);
						}
					})(field);
				}


				var div = celldiv.cloneNode(true);
				if(fil){
					div.innerHTML = '';
					div.appendChild(fil);
					fil = null;
				}

				lhtd.appendChild(div);
			}
		}

		aht.style.width = _settings.width + 'px';
		lht.style.width = _settings.lockedWidth + 'px';

		_hd = document.createElement('div');
		_hd.id = 'happyTable-header-' + _rn;
		with(_hd.style){
			position = 'relative';
			left = '0px';
			top = '0px';
			overflow = 'hidden';
			width = _settings.width + 'px';
		}

		_hd.appendChild(aht);

		_lhd = _hd.cloneNode(false);
		_lhd.style.width = _settings.lockedWidth + 'px';
		_lhd.id = 'happyTable-locked-header-' + _rn;
		_lhd.style.zIndex = 3;
		_lhd.appendChild(lht);

		return _hd;
	}

	var pager = function(){
		var p = _settings.pager;

		if(!p.pg){
			p.pg = 20;
		}

		if(!p.pi){
			p.pi = 1;
		}

		if(p.pi > p.pc){
			p.pi = p.pc;
		}

		var t = parseInt(_settings.total);
		var pc = p.pc = Math.ceil(t / p.pg);

		if(_settings.showToolbar === false || !_settings.isPaging){
			return;
		}

		var a = document.createElement('a');
		a.href = 'javascript:void(0)';
		a.style.textDecoration = 'none';

		//翻页导航条
		pd = document.createElement('div');


		if(p.pi > 1){
			var fsta = a.cloneNode(a);
			fsta.onclick = _self.pager.first;
			fsta.innerHTML = '<<&nbsp;';
			pd.appendChild(fsta);

			var preva = a.cloneNode(a);
			preva.onclick = _self.pager.prev;
			preva.innerHTML = '<&nbsp;';
			pd.appendChild(preva);

		}else{
			pd.appendChild(document.createTextNode('<< < '));
		}

		pd.appendChild(document.createTextNode(' '+p.pi+' '));

		if(p.pi < pc){
			var nxa = a.cloneNode(a);
			nxa.onclick = _self.pager.next;
			nxa.innerHTML = '>&nbsp;';
			pd.appendChild(nxa);

			var lsta = a.cloneNode(a);
			lsta.onclick = _self.pager.last;
			lsta.innerHTML = '>>&nbsp;';
			pd.appendChild(lsta);
		}else{
			pd.appendChild(document.createTextNode('> >> '));
		}

		var createPgdiv = function(e)
		{
			var e = e || event;
			var id = 'pgdiv' + _rn;

			if(getDom(id) != undefined){
				return;
			}

			var scrollY = window.pageYOffset || document.documentElement.scrollTop;
			var scrollX = window.pageXOffset || document.documentElement.scrollLeft;


			if(_view.style.marginLeft){
				scrollX -= parseInt(_view.style.marginLeft);
			}

			var pgdiv = document.createElement('div');
			var steps = [10, 20, 35, 50, 100];
			var height = 0;
			for(var i = 0; i < steps.length; i++){
				var tdiv = document.createElement('div');
				tdiv.style.width = '100%';
				tdiv.style.cursor = 'pointer';
				tdiv.innerHTML = steps[i];
				tdiv.onclick = (function(pg){
					return function(){
						_self.pager.load(null, pg);
					}
				})(steps[i]);
				pgdiv.appendChild(tdiv);
				height += 15;
			}

			pgdiv.className = _settings.css.tools;

			pgdiv.id = id;
			with(pgdiv.style){
				width='20px';
				paddingLeft = '4px';
				position='absolute';
				left=e.clientX + scrollX - 9 + 'px';
				top=e.clientY + scrollY - 80 + 'px';
				zIndex = 110;
				height = height;
			}
			var handler = function(){
				if(pgdiv.parentNode){
					pgdiv.parentNode.removeChild(pgdiv);
					pgdiv = undefined;
				}
			};

			//启动定时器，1秒后隐藏div
			var _timeout = setTimeout(handler, 1000);
			pgdiv.onmouseout = function(){
				_timeout = setTimeout(handler, 1000);
			};

			//如果鼠标在div上，清除定时器
			pgdiv.onmouseover = function(){
				clearTimeout(_timeout);
			}
			document.body.appendChild(pgdiv);
		}

		var pga = document.createElement('a');
		pga.href = 'javascript:void(0);';
		pga.onmouseover = function(ev){
			createPgdiv(ev);
		}
		pga.innerHTML = p.pg;

		pd.appendChild(document.createTextNode('共' + _settings.total + '条 '+pc+'页，每页'));
		pd.appendChild(pga);
		pd.appendChild(document.createTextNode('条 '));

		pd.style.width = '220px';
		pd.style.cssFloat = 'left';
		pd.style.styleFloat = 'left';
		_pd.add(pd);

	}

	var tools = function(){
		if(_settings.showToolbar === false){
			return;
		}
		//分页条开关div
		var xdiv = document.createElement('div');

		//分页条
		_pd = document.createElement('div');

		if(_settings.toolsVsb !== true && _settings.toolsVsb !== false){
			_settings.toolsVsb = true;
		}

		_pd.bar = document.createElement('div');
		_pd.appendChild(_pd.bar);
		with(_pd.bar.style){
			cssFloat = 'left';
			styleFloat = 'left';
		}

		_pd.add = function(t){
			_pd.bar.appendChild(t);
		}

		if(_settings.isPaging){
			_settings.toolsWidth = 280;
		}else{
			_settings.toolsWidth = 50;
		}

		pager();

        with(xdiv.style){
			position = 'absolute';
			right = '5px';
			fontSize = '15px';
			cursor = 'pointer';
		}
		xdiv.setText = function(txt){
			xdiv.innerHTML = txt;
		}
		xdiv.title = '点击隐藏';

		xdiv.onclick = function(){
			_settings.toolsVsb = (_settings.toolsVsb == true ? false : true);
			xdiv.setVsb();
			repairePosition();
		}

		xdiv.setVsb = function(){
			if(_settings.toolsVsb == false){
				_pd.style.width = '15px';
				_pd.bar.style.display = 'none';
				xdiv.title = '点击显示';
				xdiv.setText('+');
			}else{
				_pd.style.width = _settings.toolsWidth + 'px';
				xdiv.setText('-');
				xdiv.title = '点击隐藏';
				_pd.bar.style.display = 'block';
			}
		}
		_self.tools.xdiv = xdiv;

		var fbtn = document.createElement('a');
		fbtn.href = 'javascript:void(0);';
		if(_rawView){
			fbtn.innerHTML = ' 缩';
		}else{
			fbtn.innerHTML = ' 全';
		}

		fbtn.onclick = function(){
			_self.full();
		}
		var dfbtn = document.createElement('div');
		dfbtn.appendChild(fbtn);
		dfbtn.style.cssFloat = 'left';
		dfbtn.style.styleFloat = 'left';
		_pd.add(dfbtn);

		if(_rawView){
			var printbtn = fbtn.cloneNode(false);
			printbtn.onclick = function(){
				_self.tools.show(false);
				if(document.all){
					alert('注意：如果打印出现乱码，请在IE浏览器的“工具 > Internet选项 > 高级”中勾选“打印背景颜色和图像”');
				}
				window.print();
			}
			printbtn.innerHTML = '印';
			var printdiv = dfbtn.cloneNode(false);
			printdiv.style.marginLeft = '5px';
			printdiv.appendChild(printbtn);
			_pd.add(printdiv);
		}

		_pd.id = 'happyTable-pager-' + _rn;
		with(_pd.style){
			position = 'absolute';
			zIndex = 10;
			height = '15px';
			overflow = 'hidden';
			whiteSpace = 'nowrap';
		}
		_pd.className = _settings.css.tools;
		_pd.appendChild(xdiv);
		_view.appendChild(_pd);
		xdiv.setVsb();
		repairePosition();
	}

	this.decode = function(json)
	{
		return eval('(' + json + ')');
	};

	_self.configUrl = function(params){
		var ur = _settings.URL;
		for(var f in params){
			var rexp = new RegExp('&?' + f + '=[^&]*');
			ur = ur.replace(rexp, '');
			if(ur.indexOf('?') != -1){
				ur += '&';
			}else{
				ur += '?';
			}
			ur += f + '=' + encodeURI(params[f]);
		}
		_settings.URL = ur;
	}

	_self.draw = function()
	{
		mask.show('正在绘制表格，请稍候...');
		if(typeof _settings.data != 'object'){
			_settings.data = _self.decode(_settings.data);
		}

		//锁定的数据table ： locked table
		var lt = document.createElement('table');

		//活动的数据table ： active table
		var at = document.createElement('table');

		var tw = 0, ltw = 0;

		header();

		var h = _settings.header;

		var rowEvent = function(e, lr, ar, c){
			lr['on' + e] = ar['on' + e] = function(ev){
				if(e != 'click' && lr.selected){
					return;
				}

				if(e == 'click'){
					if(lr.selected){
						lr.selected = false;
						ar.selected = false;
						lr.className = ar.rawClass;
						ar.className = ar.rawClass;
						_self.fire('tr', e, ar, ev);
						return;
					}else{
						lr.selected = true;
						ar.selected = true;
					}
				}

				lr.className = c;
				ar.className = c;
				_self.fire('tr', e, ar, ev);
			}

		}

		for(var i =0; i < _settings.data.length; i++){

			var ltr = lt.insertRow(-1);
			var atr = at.insertRow(-1);
			ltr.data = _settings.data[i];
			atr.data = _settings.data[i];

			var rowClass = (ltr.rowIndex % 2 == 0) ? _settings.css.rowEven : _settings.css.rowOdd;

			ltr.className = rowClass;
			atr.className = rowClass;

			ltr.rawClass = rowClass;
			atr.rawClass = rowClass;

			rowEvent('mouseover', ltr, atr, _settings.css.rowHover);

			rowEvent('mouseout', ltr, atr, rowClass);

			rowEvent('click', ltr, atr, _settings.css.rowSelected);

			var trDraw = function(tr, locked){
				while(tr.cells[0]){
					tr.deleteCell(0);
				}

				for(var f in h){
					if(locked && !h[f].locked){
						continue;
					}
					var cw = parseInt(h[f].width) - 2;

					var atd = tr.insertCell(-1);
					atd.style.width = h[f].width + 'px';
					atd.style.height = _settings.rowHeight + 'px';

					var acelldiv = document.createElement('div');
					with(acelldiv.style){
						width = cw + 'px';
						overflow = 'hidden';
						whiteSpace = 'nowrap';
					}
					if(f != 'happyTableOperation'){
						if(h[f].mapping){
							var text = h[f].mapping[tr.data[f]];
						}else{
							var text = tr.data[f];
						}
						atd.text = document.createTextNode(text);
						atd.data = tr.data[f];
					}else{
						var opfs = _settings.op.fields;
						var tdiv = document.createElement('div');
						for(var opf in opfs){
							var tt = document.createElement('a');
							tt.href = 'javascript:void(0);';
							tt.innerHTML = opfs[opf].text;
							var lis = opfs[opf].listeners;
							for(var li in lis){
								tt['on' + li] = (function(func){
									return function(ev){
										ev = ev || event;
										func.call(this, tr, ev);
									}
								})(lis[li]);
							}
							if(tdiv.children[0]){
								tdiv.appendChild(document.createTextNode(_settings.op.splitor));
							}
							tdiv.appendChild(tt);
						}
						atd.text = tdiv;
					}

					atd.rowIndex = tr.rowIndex;

					atd.draw = (function(td){
						return function(){
							td.text.data = td.data;
						}
					})(atd);

					atd.onclick = (function(td){
						return function(ev){
							var ev = ev || window.event;
							_self.fire('td', 'click', td, ev);
						}
					})(atd);

					atd.onmouseover = (function(td){
						return function(ev){
							var ev = ev || window.event;
							_self.fire('td', 'mouseover', td, ev);
						}
					})(atd);

					atd.onmouseout = (function(td){
						return function(ev){
							var ev = ev || window.event;
							_self.fire('td', 'mouseout', td, ev);
						}
					})(atd);

					acelldiv.appendChild(atd.text);
					atd.appendChild(acelldiv);
				}

			}

			atr.remove = (function(t){
				return function(){
					_self.removeRow(t.rowIndex);
				}
			})(atr);

			ltr.remove = (function(t){
				return function(){
					_self.removeRow(t.rowIndex);
				}
			})(ltr);

			atr.draw = (function(at, lt){
				return function(){
					lt.data = at.data;
					trDraw.call(this, at);
					trDraw.call(this, lt, true);
				}
			})(atr, ltr);

			ltr.draw = (function(at, lt){
				return function(){
					at.data = lt.data;
					trDraw.call(this, at);
					trDraw.call(this, lt, true);
				}
			})(atr, ltr);

			atr.draw();
		}

		at.style.width =  _settings.width + 'px';
		at.cellSpacing = 1;
		at.cellPadding = 0;
		at.className = _settings.css.table;

		_at = at;

		lt.style.width = _settings.lockedWidth + 'px';
		lt.cellSpacing = 1;
		lt.cellPadding = 0;
		lt.className = _settings.css.table;

		_lt = lt;

		_bd = document.createElement('div');
		_bd.style.width = tw + 'px';
		_bd.style.height = '100%';
		_bd.appendChild(at);

		_lbd = _bd.cloneNode(false);
		with(_lbd.style){
			width = ltw + 'px';
			position = 'relative';
			zIndex = 1;
		}
		_lbd.appendChild(lt);


		var bs = document.createElement('div');
		bs.id = 'happyTable-bs-' + _rn;

		bs.appendChild(_hd);
		bs.appendChild(_bd);

		_view.innerHTML = '';

		_view.appendChild(bs);

		var lbs = document.createElement('div');
		lbs.id = 'happyTable-lbs-' + _rn;
		lbs.style.position = 'absolute';
		lbs.style.zIndex = 2;
		lbs.style.top = '0px';

		lbs.appendChild(_lhd);
		lbs.appendChild(_lbd);
		_view.appendChild(lbs);

		tools();
		repairePosition();
		mask.hide();
	}

	this.decode = function(json)
	{
		return eval('(' + json + ')');
	};

	this.show = function(){
		_load();
		var handler = function(){
			if(_loaded){
				clearInterval(si);
				_self.draw();
			}
		}

		var si = setInterval(handler, 100);
	};

	this.removeRow = function(rowIndex){
		try{
			_lt.deleteRow(parseInt(rowIndex));
			_at.deleteRow(parseInt(rowIndex));
		}catch(e){}
	};

	this.insertRow = function(data, rowIndex){
		var isLast = (rowIndex == undefined || rowIndex == -1 || rowIndex > data.length - 1) ? true : false;
		if(isLast){
			_settings.data[_settings.data.length] = data;
			_self.draw();
			return;
		}
		var tdata = [];
		var i = 0;
		var fd;
		while(i < _settings.data.length){
			if(!fd && i == rowIndex){
				tdata[tdata.length] = data;
				fd = true;
				continue;
			}
			tdata[tdata.length] = _settings.data[i];
			i += 1;
		}
		_settings.data = tdata;
		_self.draw();
		rowIndex = isLast ? -1 : rowIndex;
		return _self.getRow(rowIndex);
	};

	this.getRow = function(rowIndex){
		if(rowIndex == -1){
			rowIndex = _at.rows[_at.rows.length - 1]
		}
		try{
			return _at.rows[rowIndex];
		}catch(e){
			return undefined;
		}
	}

	_self.sort = function(f, order){
		var ff = _settings.header[f] || null;
		if(!ff){
			return ff;
		}

		var ot = ['asc', 'desc'];
		if(ot.indexOf(order) != -1){
			ff.order = order;
		}else{
			ff.order = (ff.order == 'asc' ? 'desc' : 'asc');
		}


		var d = _settings.data;
		var t = [];

		for(var i = 0; i < d.length; i++){
			t[t.length] = d[i][f];
		}

		t.sort(function(a, b){
			if(ff.order == 'asc'){
				return a > b ? 1 : (a < b ? -1 : 0);
			}

			return a < b ? 1 : (a > b ? -1 : 0);
		});

		var r = [], sorted = [];
		for(var i = 0; i < t.length; i++){
			for(var j = 0; j < d.length; j++){
				if(d[j][f] == t[i] && sorted.indexOf(j) == -1){
					sorted[sorted.length] = j;
					r[i] = d[j];
					break;
				}
			}
		}
		_settings.data = r;
		_self.draw();
	}

	_self.getTotal = function(){
		return _settings.total;
	};

	_self.pager = {};

	_self.pager.setUrl = function(){
		var ur = _settings.URL;
		if(_settings.pager && _settings.pager.pi){
			var exppi = '_pi=' + _settings.pager.pi;
			if(ur.match(/_pi=\d*/)){
				ur = ur.replace(/_pi=\d*/, exppi);
			}else{
				ur += ur.indexOf('?') > 0 ? '&' : '?';
				ur += exppi;
			}
		}

		if(_settings.pager && _settings.pager.pg){
			var exppg = '_pg=' + _settings.pager.pg;
			if(ur.match(/_pg=\d*/)){
				ur = ur.replace(/_pg=\d*/, exppg);
			}else{
				ur += ur.indexOf('?') > 0 ? '&' : '?';
				ur += exppg;
			}
		}
		_settings.URL = ur;
	}

	_self.pager.load = function(pi, pg){
		if(pi){
			_settings.pager.pi = pi;
		}

		if(pg){
			_settings.pager.pg = pg;
		}
		_self.show();
	}

	_self.pager.prev = function(){
		_settings.pager.pi -= 1;
		if(_settings.pager.pi < 1){
			_settings.pager.pi = 1;
		}
		_self.show();
	};

	_self.pager.first = function(){
		_settings.pager.pi = 1;
		_self.show();
	};

	_self.pager.next = function(){
		_settings.pager.pi += 1;
		if(_settings.pager.pi > _settings.pager.pc){
			_settings.pager.pi = _settings.pager.pc;
		}
		_self.show();
	}

	_self.pager.last = function(){
		_settings.pager.pi = _settings.pager.pc;
		_self.show();
	}

	_self.pager.pageIndex = _settings.pager.PI;
	_self.pager.perPage = _settings.pager.pg;

	//如果 s == true，显示分页条
	_self.tools = {};
	_self.tools.show = function(s){
		_settings.toolsVsb = s;
		_self.tools.xdiv.setVsb();
		repairePosition();
	};

	_self.event = {};

	//注册事件
	_self.on = function(o, e, f){
		var os = ['tr', 'td', 'view'];
		if(os.indexOf(o) == -1){
			return;
		}

		var es = ['click', 'mouseover', 'mouseout', 'scroll'];
		if(es.indexOf(e) == -1){
			return;
		}

		if(!_self.event[o]){
			_self.event[o] = {};
		}
		_self.event[o][e] = f;
	};

	/**
	触发对象o上的事件
	o 事件标签名,如tr td等
	e 事件名,如click mouseover等
	t 事件宿主
	ev 事件对象
	*/
	_self.fire = function(o, e, t, ev){
		if(!_self.event[o]){
			return;
		}

		if(!_self.event[o][e]){
			return;
		}
		_self.event[o][e].call(this, t, ev);
	};

	_self.full = function(){
		_select();
		if(_rawView){
			var fbg = getDom('happyTableFull' + _rn);
			fbg.removeChild(_view);
			document.body.removeChild(fbg);
			fbg = null;
			_view = _rawView;
			initView();
			_rawView = undefined;
			window.onscroll = window.rawOnscroll;
			_self.draw();
			return;
		}
		var fbg = document.createElement('div');
		fbg.id = 'happyTableFull' + _rn;
		var fheight = document.body.clientHeight > document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight;
		var stl = {zIndex:100,position:'absolute',left:'0px', top:'0px',height:fheight + 'px',width:document.body.scrollWidth + 'px', backgroundColor:'white'};
		for(var pro in stl){
			fbg.style[pro] = stl[pro];
		}
		document.body.appendChild(fbg);
		var newView = document.createElement('div');
		with(newView.style){
			width = _settings.width + 'px';
			height = (_settings.rowHeight * (_settings.data.length + 1)).toString() + 'px';
			marginLeft = '20px';
			position = 'absolute';
		}
		fbg.appendChild(newView);
		_rawView = _view;
		_view = newView;
		initView();
		window.rawOnscroll = window.onscroll;
		window.onscroll = repairePosition;
		_self.draw();
	}
}
